package com.me.launcher.db;

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;

import com.me.launcher.bean.AppBean;
import com.me.launcher.tools.LogUtil;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author hejiangwei
 * @date 2018/5/10 0008
 */
public class DBUtil {
    private static final String TAG = "DBUtil";
    private volatile static DBUtil single = null;
    private DataBaseDriver mDataBaseDriver;
    private Context mContext;

    private DBUtil(Context context) {
        mContext = context;

    }

    public static DBUtil getInstance(Context context) {
        if (single == null) {
            synchronized (DBUtil.class) {
                if (single == null) {
                    single = new DBUtil(context);
                }
            }
        }
        return single;
    }

    /**
     * @return 获取所有app的个数，不包含空app与快捷方式
     */
    public int getSizeApps() {
        if (!Open()) {
            Close();
            return 0;
        }
        String SqlHasWordBook = "select * from tbl_apps where name is not null and intent = ''";
        Cursor cursorIsSame = mDataBaseDriver.QuerySQL(SqlHasWordBook);
        int size = cursorIsSame.getCount();
        cursorIsSame.close();
        Close();
        return size;
    }

    public boolean Open() {

        String strSQLTXT = "create table if not exists tbl_apps("
                + "id integer primary key autoincrement,"
                + "name text,"
                + "app_index integer,"
                + "page_index integer,"
                + "intent text)";

        String strFile = mContext.getFilesDir() + "/apps.db";

        LogUtil.e(TAG, "Open===" + strFile);
        mDataBaseDriver = new DataBaseDriver(mContext, strFile);


        boolean bRet = mDataBaseDriver.ExecuteSQL(strSQLTXT);
        if (bRet == false) {
            return false;
        }


        return true;
    }

    public synchronized void Close() {
        mDataBaseDriver.Close();
    }


    /**
     * @return 获取数据库中的一页的app个数
     */
    public int getNumOfScreen() {
        int num = 0;

        if (!Open()) {
            Close();
            return num;

        }

        String sql = "select name from tbl_apps where page_index = 0";
        Cursor cursorApp = mDataBaseDriver.QuerySQL(sql);

        num = cursorApp.getCount();
        cursorApp.close();
        Close();
        return num;
    }

    /**
     * @return 获取快捷方式的集合
     */
    public List<AppBean> getShortCut() {
        List<AppBean> appBeans = null;
        if (!Open()) {
            Close();
            return appBeans;
        }
        appBeans = new ArrayList<>();
        String SqlHasWordBook = "select * from tbl_apps where intent != ''";
        Cursor cursorApp = mDataBaseDriver.QuerySQL(SqlHasWordBook);
        if (cursorApp.getCount() > 0) {

            cursorApp.moveToFirst();
            do {
                appBeans.add(new AppBean.Builder()
                        .name(cursorApp.getString(cursorApp.getColumnIndex("name")))
                        .intent(cursorApp.getString(cursorApp.getColumnIndex("intent")))
                        .build());


            } while (cursorApp.moveToNext());
        }
        cursorApp.close();
        Close();
        return appBeans;

    }

    /**
     * 删除表中所有数据
     */
    public void deleteAllApps() {
        if (!Open()) {
            Close();
            return;
        }
        String SqlHasWordBook = "delete from tbl_apps";
        mDataBaseDriver.ExecuteSQL(SqlHasWordBook);
        Close();
    }

    /**
     * 删除表中热键区数据
     */
    public void deleteBottomApps() {
        if (!Open()) {
            Close();
            return;
        }
        String SqlHasWordBook = "delete from tbl_apps where page_index = -1";
        mDataBaseDriver.ExecuteSQL(SqlHasWordBook);
        Close();
    }

    /**
     * 删除表中apps所有数据
     */
    public void deleteAppsApp() {
        if (!Open()) {
            Close();
            return;
        }
        String SqlHasWordBook = "delete from tbl_apps where page_index > -1";
        mDataBaseDriver.ExecuteSQL(SqlHasWordBook);
        Close();
    }

    /**
     * 在apps区域放置app
     */
    public void setAppsApp(int[] indexs, AppBean app) {
        if (!Open()) {
            Close();
            return;
        }
        String updata = String.format("update tbl_apps set name = '%s', intent = '%s' where page_index = %d and app_index = %d",
                app.getStrName(), app.getIntent(), indexs[0], indexs[1]);

        mDataBaseDriver.ExecuteSQL(updata);

        Close();
    }

    /**
     * 放置快捷方式
     *
     * @param app 快捷方式对象
     * @return 返回放置位置
     * 先放置于最后一页，如果没有位置再从前面寻找位置
     */
    public List<Integer> setAppsApp(AppBean app) {
        List<Integer> indexArr = new ArrayList<>();
        if (!Open()) {
            Close();
            return indexArr;
        }
        String Sqlindex = "select MAX(page_index) from tbl_apps";
        Cursor cursorSqlindex = mDataBaseDriver.QuerySQL(Sqlindex);
        cursorSqlindex.moveToNext();

        //最后一页
        int page = cursorSqlindex.getInt(0);
        cursorSqlindex.close();
        String SqlHasWordBook = String.format("select * from tbl_apps where page_index = %d order by app_index asc", page);
        Cursor cursorApp = mDataBaseDriver.QuerySQL(SqlHasWordBook);
        cursorApp.moveToFirst();
        int index = -1;
        if (cursorApp.getCount() > 0) {
            do {
                if (TextUtils.isEmpty(cursorApp.getString(cursorApp.getColumnIndex("name")))) {
                    if (index < 0) index = cursorApp.getInt(cursorApp.getColumnIndex("app_index"));
                    break;
                }

            } while (cursorApp.moveToNext());

        }
        cursorApp.close();
        String updata = null;


        if (index < 0) {
            List<Integer> indexs = getAllIndex(page, app);
            if (indexs == null || indexs.isEmpty()) {
                cursorApp.close();
                Close();
                return indexArr;
            } else {
                indexArr.addAll(indexs);

            }
        } else {
            indexArr.add(page);
            indexArr.add(index);
        }
        updata = String.format("update tbl_apps set name = '%s', intent = '%s' where app_index = %d and page_index = %d",
                app.getStrName(), app.getIntent(), indexArr.get(1), indexArr.get(0));

        if (mDataBaseDriver.ExecuteSQL(updata)) {

        } else {
            indexArr.clear();
        }

        Close();
        return indexArr;
    }

    /**
     * @param maxIndex 最大页索引
     * @param app
     * @return 获取放置空位坐标
     */
    private List<Integer> getAllIndex(int maxIndex, AppBean app) {
        if (!Open()) {
            Close();
            return null;
        }
        List<Integer> indexArr = new ArrayList<>();
//        boolean hasSame = false;

        for (int i = 0; i < maxIndex; i++) {
            String SqlHasWordBook = String.format("select * from tbl_apps where page_index = %d order by app_index asc", i);
            Cursor cursorApp = mDataBaseDriver.QuerySQL(SqlHasWordBook);
            cursorApp.moveToFirst();
            int index = -1;
            if (cursorApp.getCount() > 0) {
                do {
                    if (TextUtils.isEmpty(cursorApp.getString(cursorApp.getColumnIndex("name")))) {
                        if (index < 0)
                            index = cursorApp.getInt(cursorApp.getColumnIndex("app_index"));
                            break;
                    }
//                    else {
//                        if (TextUtils.equals(cursorApp.getString(cursorApp.getColumnIndex("name")), app.getStrName()) &&
//                                TextUtils.equals(cursorApp.getString(cursorApp.getColumnIndex("intent")), app.getIntent())) {
//                            hasSame = true;
//                        }
//                    }

                } while (cursorApp.moveToNext());

            }
            cursorApp.close();
//            if (hasSame) {
//                indexArr.clear();
//                break;
//            }
            if (index >= 0 && indexArr.isEmpty()) {
                indexArr.add(i);
                indexArr.add(index);
            }

        }

        Close();
        return indexArr;
    }

    /**
     * 查询某列是否存在，如果不存在则删除数据表重建
     */
    public void checkColumnExists() {
        boolean result = false;
        if (!Open()) {
            Close();
            return;
        }
        Cursor cursor = mDataBaseDriver.QuerySQL("select * from tbl_apps");

        cursor.moveToFirst();
        if (cursor.getColumnIndex("intent") >= 0) {
            result = true;
        }
        if (null != cursor && !cursor.isClosed()) {
            cursor.close();
        }
        if (!result) {
            //更新数据
            List<List<AppBean>> apps = getApps();
            List<AppBean> bottom = getBottomApps();
            deleteTable();
            addAppsApp(apps);
            addBottomApp(bottom);
        }
        Close();
    }

    /**
     * 获取apps区域的app
     *
     * @return 返回app的name集合
     */
    public List<List<AppBean>> getApps() {
        List<List<AppBean>> mShowApps = new ArrayList<>();
        if (!Open()) {
            Close();
            return mShowApps;
        }

        String Sqlindex = "select MAX(page_index) from tbl_apps";
        Cursor cursorSqlindex = mDataBaseDriver.QuerySQL(Sqlindex);
        cursorSqlindex.moveToNext();
        int page = cursorSqlindex.getInt(0);
        cursorSqlindex.close();
        for (int i = 0; i <= page; i++) {
            List<AppBean> list = new ArrayList<>();
            String SqlHasWordBook = String.format("select * from tbl_apps where page_index = %d order by app_index asc", i);
            Cursor cursorApp = mDataBaseDriver.QuerySQL(SqlHasWordBook);
            cursorApp.moveToFirst();
            if (cursorApp.getCount() > 0) {

                do {
                    if (TextUtils.isEmpty(cursorApp.getString(cursorApp.getColumnIndex("name")))) {
                        list.add(new AppBean.Builder().build());
                    } else {
                        if (cursorApp.getColumnIndex("intent") < 0 || TextUtils.isEmpty(cursorApp.getString(cursorApp.getColumnIndex("intent")))) {
                            list.add(new AppBean.Builder().type(AppBean.AppType.LAUNCH_APP)
                                    .name(cursorApp.getString(cursorApp.getColumnIndex("name")))
                                    .build());

                        } else {
                            list.add(new AppBean.Builder().type(AppBean.AppType.LAUNCH_SHORT_CUT)
                                    .name(cursorApp.getString(cursorApp.getColumnIndex("name")))
                                    .intent(cursorApp.getString(cursorApp.getColumnIndex("intent")))
                                    .build());

                        }


                    }


                } while (cursorApp.moveToNext());
            }

            cursorApp.close();
            mShowApps.add(list);
        }


        Close();
        return mShowApps;
    }

    /**
     * 获取bottom区域的app
     *
     * @return 返回app的name集合
     */
    public List<AppBean> getBottomApps() {
        List<AppBean> mBottomApps = new ArrayList<>();
        if (!Open()) {
            Close();
            return mBottomApps;
        }

        String SqlHasWordBook = "select * from tbl_apps where page_index = -1 order by app_index asc";
        Cursor cursorApp = mDataBaseDriver.QuerySQL(SqlHasWordBook);
        if (cursorApp.getCount() > 0) {

            cursorApp.moveToFirst();
            do {

                if (TextUtils.isEmpty(cursorApp.getString(cursorApp.getColumnIndex("name")))) {
                    mBottomApps.add(new AppBean.Builder().build());
                } else {
                    if (cursorApp.getColumnIndex("intent") < 0 || TextUtils.isEmpty(cursorApp.getString(cursorApp.getColumnIndex("intent")))) {
                        mBottomApps.add(new AppBean.Builder().type(AppBean.AppType.LAUNCH_APP)
                                .name(cursorApp.getString(cursorApp.getColumnIndex("name")))
                                .build());

                    } else {
                        mBottomApps.add(new AppBean.Builder().type(AppBean.AppType.LAUNCH_SHORT_CUT)
                                .name(cursorApp.getString(cursorApp.getColumnIndex("name")))
                                .intent(cursorApp.getString(cursorApp.getColumnIndex("intent")))
                                .build());

                    }


                }
            } while (cursorApp.moveToNext());
        }

        cursorApp.close();


        Close();
        return mBottomApps;
    }

    public void deleteTable() {
        if (!Open()) {
            Close();
            return;
        }
        String SqlHasWordBook = "DROP TABLE tbl_apps";
        mDataBaseDriver.ExecuteSQL(SqlHasWordBook);
        Close();
    }

    public void addAppsApp(List<List<AppBean>> mapps) {
        if (!Open()) {
            Close();
            return;
        }
        for (int i = 0; i < mapps.size(); i++) {
            for (int i1 = 0; i1 < mapps.get(i).size(); i1++) {
                String strSQL = "insert into tbl_apps" +
                        "(name,app_index,page_index,intent)" +
                        "values(?,?,?,?)";
                Object[] mValue = new Object[]{
                        (mapps.get(i).get(i1) == null) ? null : mapps.get(i).get(i1).getStrName(),
                        i1, i,
                        (mapps.get(i).get(i1) == null) ? null : (mapps.get(i).get(i1).getIntent() == null ? null : mapps.get(i).get(i1).getIntent())};
                mDataBaseDriver.execSQL(strSQL, mValue);

            }

        }
        Close();
    }

    public void addBottomApp(List<AppBean> mbottoms) {
        if (!Open()) {
            Close();
            return;
        }
        if (mbottoms.size() > 5) {
            LogUtil.e(TAG, "addBottomApp====" + mbottoms.size());
            if (mbottoms.get(2).getActivityInfo() == null && mbottoms.get(3).getActivityInfo() == null) {
                mbottoms.remove(2);
            }
        }
        for (int i = 0; i < mbottoms.size(); i++) {
            String strSQL = "insert into tbl_apps" +
                    "(name,app_index,page_index,intent)" +
                    "values(?,?,?,?)";
            Object[] mValue = new Object[]{
                    (mbottoms.get(i) == null) ? null : mbottoms.get(i).getStrName(),
                    i, -1,
                    (mbottoms.get(i) == null) ? null : (mbottoms.get(i).getIntent() == null ? null : mbottoms.get(i).getIntent())};
            mDataBaseDriver.execSQL(strSQL, mValue);

        }
        Close();
    }

}
